package com.iot08.push.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.common.constant.Const;
import com.iot08.common.constant.ConstPush;
import com.iot08.common.utils.StringUtil;
import com.iot08.push.mob.MobConfig;
import com.iot08.push.mob.MyPushWorkBuilder;
import com.iot08.push.utils.MobVO;
import com.iot08.push.utils.PushSendVO;
import lombok.extern.slf4j.Slf4j;
import mob.push.api.client.push.PushV3Client;
import mob.push.api.http.Result;
import mob.push.api.model.Push;
import mob.push.api.res.PushV3Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description: 异步推送业务处理
 * @time: 2021/1/20 14:02
 * @author: Rock
 */
@Slf4j
@Service
public class AsyncService {

    @Autowired
    public MobConfig mobConfig;

    /**
     * 异步推送mob
     *
     * @param mobs
     * @param vo
     * @param extraMap
     * @param data
     * @time: 2021/1/20 14:15
     * @author: Rock
     * @version 1.0
     */
    @Async
    public void asyncSendMob(List<MobVO> mobs, PushSendVO vo, Map<String, String> extraMap, JSONObject data) {
        if (mobs.size() > 0) {
            JSONObject mes = data.getJSONObject(ConstPush.MESSAGE);
            if ("video".equals(vo.getType()) || "unbind".equals(vo.getType())
                    || "unfriend".equals(vo.getType()) || "reject".equals(vo.getType() )|| "videoGroup".equals(vo.getType())) {
                if (StringUtil.isNotBlank(mes)) {
                    String openid = mes.getString(ConstPush.OPENID);
                    if ("videoGroup".equals(vo.getType())) {
                        // 群视频不需要过滤，推送给所有目标用户
                        log.info("群视频通话，推送给所有目标用户");
                    } else if (StringUtil.isNotBlank(openid)) {
                        MobVO mobVO = null;
                        for (MobVO mob : mobs) {
                            if (openid.equals(mob.getAlias())) {
                                mobVO = mob;
                                break;
                            }
                        }
                        mobs.clear();
                        if (mobVO != null) {
                            mobs.add(mobVO);
                        }
                    }
                }
            }
            Result<PushV3Res> resResult = null;
            String pushType = vo.getType();
            log.info("发送Mob的推送消息pushType:{},携带的拓展消息 mobs:{} extraMap:{} ", pushType, mobs.toString(), JSONObject.toJSONString(extraMap));
            for (MobVO mob : mobs) {
                if (StringUtil.isNotBlank(mob.getAlias()) && StringUtil.isNotBlank(vo.getAlert())) {
                    String dataStr = "";
                    if (Const.INT_1.equals(mob.getPlatform())) {
                        dataStr = vo.getAndroidData().toJSONString();
                    } else {
                        dataStr = vo.getData().toJSONString();
                    }
                    //TODO 根据每一条消息的包名packageName 判断是否切换配置Key
                    String scheme = mobConfig.setConfigWithPackageNameAndGetScheme(mob.getPackageName(), mob.getPlatform());
                    if (scheme == null) {
                        log.error("错误为null的 scheme不发推送");
                        return;
                    }
                    if (pushType != null && pushType.contentEquals("LoginOffLine")) {
                        try {
                            log.info("-------------------推送mob消息，推送内容：-------------------"+dataStr+",extraMap:"+extraMap+"RegistrationID:"+mob.getOldRegistrationID());
                            Push push = new MyPushWorkBuilder().setTargetByRids(vo.getAlert(), scheme, dataStr,
                                            mob.getPlatform(), mob.getIosProduction(), extraMap, mob.getOldRegistrationID()).build();
                            resResult = PushV3Client.pushTaskV3(push);
                            log.info("----------------推送数据的对象及内容----------------{}",JSONObject.toJSONString(push));
                            log.info("-------------------推送mob消息结果：-------------------"+resResult);
                        } catch (Exception error) {
                            log.error("发送Mob 推送报错:" + error.getMessage() + " 重试一下", error);
                            log.info("-------------------推送mob消息，推送内容：-------------------"+dataStr+",extraMap:"+extraMap+",RegistrationID:"+mob.getOldRegistrationID());
                            resResult = PushV3Client.pushTaskV3(new MyPushWorkBuilder()
                                    .setTargetByRids(vo.getAlert(), scheme, dataStr,
                                            mob.getPlatform(), mob.getIosProduction(), extraMap, mob.getOldRegistrationID())
                                    .build());
                            log.info("-------------------重新推送mob消息结果：-------------------"+resResult);
                        }
                    } else {
                        try {
                            log.info("-------------------推送mob消息，推送内容：-------------------"+dataStr+",extraMap:"+extraMap+",Alias:"+mob.getAlias());
                            Push push = new MyPushWorkBuilder().setTargetByAlias(vo.getAlert(), scheme, dataStr,
                                            mob.getPlatform(), mob.getIosProduction(), extraMap, mob.getAlias()).build();
                            resResult = PushV3Client.pushTaskV3(push);
                            log.info("----------------推送数据的对象及内容----------------{}",JSONObject.toJSONString(push));
                            log.info("-------------------推送mob消息结果：-------------------"+resResult);
                        } catch (Exception error) {
                            log.error("发送Mob 推送报错:" + error.getMessage() + " 重试一下", error);
                            log.info("-------------------推送mob消息，推送内容：-------------------"+dataStr+",extraMap:"+extraMap+",Alias:"+mob.getAlias());
                            resResult = PushV3Client.pushTaskV3(new MyPushWorkBuilder()
                                    .setTargetByAlias(vo.getAlert(), scheme, dataStr,
                                            mob.getPlatform(), mob.getIosProduction(), extraMap, mob.getAlias()).build());
                            log.info("-------------------重新推送mob消息结果：-------------------"+resResult);
                        }
                    }
                    if (resResult == null || !resResult.success()) {
                        log.error("mobpush alias is fail. alias={}. data = {}", mob.getAlias(), data);
                    }
                }
            }
        }
    }

}
